<?php


namespace App\Remote\Rms;

use App\Enums\BaseErrorCode;
use App\Exceptions\Custom\ResponseHttpException;
use App\Remote\Remote;
use App\Service\OpenShop\User\RmsUserService;
use Closure;
use Kuafu\IpWhite\Service\IpWhiteService;
use Psr\Container\ContainerExceptionInterface;
use Psr\Container\NotFoundExceptionInterface;
use Symfony\Component\HttpFoundation\Response as ResponseAlias;


class BaseRmsRemote extends Remote
{

    public static function getBaseUri(): string
    {
        // TODO: Implement getBaseUri() method.
        return config('rms.domain');
    }


    /**
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface
     */
    public static function buildBasicHeaders(): array
    {
        $headers = getRequest()->headers;
        return [
            "authorization"  => $headers->get("authorization"),
            "brandId"        => $headers->get("brandId"),
            "shopId"         => $headers->get("shopId"),
            'internal-key'   => config('rms.internalKey'),
            'internal-token' => config('rms.internalValue'),
            'userId'         => getRmsUserId(),
            'Content-Type'   => 'application/json'
        ]; // TODO: Change the autogenerated stub
    }

    /**
     * @return Closure
     */
    public static function registerResponseHandle(): Closure
    {
        return function (string $data) {
            $response = json_decode($data, true);
            if ($response["code"] == ResponseAlias::HTTP_OK) {
                return $response["data"];
            } else {

                $code = BaseErrorCode::$ERROR_REMOTE_RMS_RESPONSE;
                $msg  = "RMS [ {$response["msg"]} ]";

                // 被踢下线特殊处理
                if ($response['code'] == IpWhiteService::ERR_RESPONSE_CODE) {
                    $code = IpWhiteService::ERR_RESPONSE_CODE;
                    $msg  = $response["msg"] ?? IpWhiteService::ERR_RESPONSE_MSG;
                }

                throw new ResponseHttpException(
                    $code,
                    null,
                    $msg,
                );
            }
        };
        // TODO: Change the autogenerated stub
    }
}
